//
//  AppDelegate.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "AppDelegate.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#define SERV_PORT 27350
#pragma mark
#pragma mark init
#import "HOTabViewController.h"
#import "HOLoginViewController.h"
#import "HORootViewController.h"
#import "HONavigationController.h"
#import "HOUIMgr.h"
#import "HOGlobalData.h"
//#import "UMSocialWechatHandler.h"
//#import "UMSocialSinaSSOHandler.h"
//#import "UMSocialFacebookHandler.h"
//#import "UMSocialTwitterHandler.h"
//#import "UMSocial.h"
#import "HOUtils.h"
#import "Logger.h"
#import "HOConstants.h"
#import "HOAnalyzeViewController.h"
#import "HOStaticDataMgr.h"
#import "HOGlobalData.h"
#import "HOJPushHandler.h"

// 引入 JSHARE 功能所需头文件
#import "JSHAREService.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#import "HOStaticDataMgr.h"

@interface AppDelegate ()
{
	UIButton		*urgencyLbl;
}
@property(nonatomic, retain)NSTimer *urgencyViewHideTimeout;
@property(nonatomic, assign)BOOL isReceivedPushWhenAppInBackground;

@property(nonatomic, assign)BOOL isForeground;
@end

@implementation AppDelegate

- (void)redirectNSlogToDocumentFolder
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"WeiduTrace_%@.log", [HOUtils getCurrentDateForFileName]];// 注意不是NSData!
    
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
    // 先删除已经存在的文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    [defaultManager removeItemAtPath:logFilePath error:nil];
    
    
    // 将log输入到文件
    
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
    
}

- (void)initJShare
{
	JSHARELaunchConfig *config = [[JSHARELaunchConfig alloc] init];
	config.appKey = mJPushAppKey;

	config.QQAppId = @"1106808840";
	config.QQAppKey = @"YgtbdOulcELwDJu6";
	config.WeChatAppId = @"wx9d528a0cf2bb9baf";
	config.WeChatAppSecret = @"c2bde1a634d00a30e3efb3b9e4ed68da";
	
	[JSHAREService setupWithConfig:config];
	[JSHAREService setDebug:YES];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
	
	NSLog(@"applicationDidReceiveMemoryWarning----------");
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//	[self redirectNSlogToDocumentFolder];
	[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
	[JPUSHService setBadge:0];
	[self initJShare];
	NSLog(@"----didFinishLaunchingWithOptions: dic%@", launchOptions);
#pragma mark
	[self initUIStyle];
//	return YES;
#pragma mark
#pragma mark Fabric
    [Fabric with:@[CrashlyticsKit]];
	[Fabric sharedSDK].debug = NO;
    //	[[Crashlytics sharedInstance] crash];
#pragma mark
	
#pragma mark JPUSH
    [[HOUIMgr sharedInstance] checkNotification];
	//[self deviceRegisterPush];
	[[HOJPushHandler sharedInstance] registerJPushServiceWithOptions:launchOptions];
	[[HOJPushHandler sharedInstance] initJPushServiceWithOptions:launchOptions];
	[[HOJPushHandler sharedInstance] addObserveJPushNotifications];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:kHO_CMD_UrgencyMessage object:nil];
#pragma mark - -- Start app
	
	[HOGlobalData sharedInstance].isNeedCheckVersion = YES;
	[[HOUIMgr sharedInstance] checkToken];
	UIViewController *viewCtrl = [[HOUIMgr sharedInstance] getFirstViewController];
	if(launchOptions != nil)
	{
		[HOStaticDataMgr sharedInstance].openAppFromPushMessage = YES;
	}
	HONavigationController *navCtrl = [[HONavigationController alloc] initWithRootViewController:viewCtrl];
	self.window.rootViewController = navCtrl;
	[navCtrl release];
	
	[[HOUIMgr sharedInstance] checkVersion];

#pragma mark Social
	[self initSocial];
#pragma mark
	
    return YES;
}

#pragma mark
#pragma mark engercy view
- (void)receiveNotification:(NSNotification *)notification
{
	if(![HOGlobalData sharedInstance].isLoggedin)
		return;
	NSDictionary *useInfo = notification.userInfo;
//	int type = [[useInfo valueForKey:@"type"] intValue];
//	if(type != HO_NC_TYPE_ORDER_PAY)
//		return;
	self.urgencyViewHideTimeout = [NSTimer scheduledTimerWithTimeInterval:3
																   target:self selector:@selector(hideEngeryView:)
																 userInfo:nil
																  repeats:NO];
	if(urgencyLbl == nil)
	{
		urgencyLbl= [[UIButton alloc]
					 initWithFrame:CGRectMake(0.0,
											  0.0,
											  [UIScreen mainScreen].bounds.size.width,
											  20.0)];
		urgencyLbl.backgroundColor = UIColorFromRGB(0xf27a39);
		[urgencyLbl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//		urgencyLbl.textAlignment = NSTextAlignmentCenter;
		urgencyLbl.font = [UIFont systemFontOfSize:14];
		[self.window.rootViewController.view addSubview:urgencyLbl];
		[urgencyLbl addTarget:self action:@selector(didClickUrgencyBtn:) forControlEvents:UIControlEventTouchUpInside];
	}
	urgencyLbl.hidden = NO;
	[[[[UIApplication sharedApplication] delegate] window] setWindowLevel:UIWindowLevelStatusBar+1];
//	NSDictionary *dic = [useInfo objectForKey:@"aps"];
	[urgencyLbl setTitle:@"您有新的消息，请注意查收!" forState:UIControlStateNormal];
//	if(dic)
//	{
//		urgencyLbl.text = [dic objectForKey:@"alert"];
//	}
}

- (void)didClickUrgencyBtn:(id)sender
{
	if(![HOGlobalData sharedInstance].isLoggedin)
		return;
	[[HOUIMgr sharedInstance] sendCommand:kHO_CMD_OpenMessageFromUrgency data:nil];
}


- (void)hideEngeryView:(NSTimer *)timer
{
	urgencyLbl.hidden = YES;
	[[[[UIApplication sharedApplication] delegate] window] setWindowLevel:UIWindowLevelNormal];
	[self cancelEngeryTimeout];
}

- (void)cancelEngeryTimeout
{
	if(self.urgencyViewHideTimeout)
	{
		[self.urgencyViewHideTimeout invalidate];
		self.urgencyViewHideTimeout = nil;
	}
}
#pragma mark
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
	//Optional
	LogErr(@"did Fail To Register For Remote Notifications With Error: %@", err);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
	static BOOL isRegistedBefore;
	if(isRegistedBefore)
		return;
	isRegistedBefore = YES;
	
	
	
//    NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken deviceToken:%@", deviceToken);
    [[HOGlobalData sharedInstance] saveDeviceToken:deviceToken];
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Required
    [JPUSHService handleRemoteNotification:userInfo];  // Required,For systems with less than or equal to iOS6
    [[HOUIMgr sharedInstance] didReceiveRemoteNotification:userInfo];
	if(!self.isForeground)
	{
		self.isReceivedPushWhenAppInBackground = YES;
	}
	else
	{
		
		self.isReceivedPushWhenAppInBackground = NO;
	}
}
//iOS 7 Remote Notification

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)   (UIBackgroundFetchResult))completionHandler
{
	if(!self.isForeground)
	{
		self.isReceivedPushWhenAppInBackground = YES;
	}
	else
	{
		self.isReceivedPushWhenAppInBackground = NO;
	}
	//震动
	[HOUtils playMidi];
    // Required
	[[HOUIMgr sharedInstance] getNewMessage];
	[JPUSHService handleRemoteNotification:userInfo];// Required, iOS 7 Support
	[[HOUIMgr sharedInstance] didReceiveRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNoData);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [HOGlobalData sharedInstance].isNeedCheckVersion = YES;
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [HOGlobalData sharedInstance].isPopedUpAlertForNotifaction = NO;
	self.isForeground = NO;
	self.isReceivedPushWhenAppInBackground = NO;

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [HOGlobalData sharedInstance].isNeedCheckVersion = YES;
    [HOGlobalData sharedInstance].isPopedUpAlertForVersion = NO;
    [[HOUIMgr sharedInstance] checkNotification];
    [[HOUIMgr sharedInstance] checkVersion];
	[HOGlobalData sharedInstance].dontNeedUpdateInfoAfterAppEnterFront = NO;
//    [[HOUIMgr sharedInstance] getNewMessage];
	if([HOGlobalData sharedInstance].isLoggedin)
	{
		[[[HOUIMgr sharedInstance] getController:HO_MODULE_TYPE_APP] sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_UploadJpush,kHO_FIELD_JPushRegisterID:[[HOJPushHandler sharedInstance] getRegistertationID]}];
	}

	[[HOUIMgr sharedInstance] sendCommand:kHO_CMD_WillEnterForeground data:nil];
	self.isForeground = YES;
	

	
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
	self.isForeground = YES;
	[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
	[JPUSHService setBadge:0];

	if([HOGlobalData sharedInstance].isLoggedin)
	{
		[[[HOUIMgr sharedInstance] getController:HO_MODULE_TYPE_APP] sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_UploadJpush,kHO_FIELD_JPushRegisterID:[[HOJPushHandler sharedInstance] getRegistertationID]}];
		
		if(self.isReceivedPushWhenAppInBackground)
		{
//			[self didClickUrgencyBtn:nil];
		}
		self.isReceivedPushWhenAppInBackground = YES;
	}
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

/**
 APP重新进入版通知设置
 */


/**
 * 推送处理2(接收所有远程通知)
 */
//注册用户通知设置
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings
{
	// register to receive notifications
	[application registerForRemoteNotifications];//注册远程通知
}


/**
 接收本地通知
 */
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
	[JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
	//震动
	[HOUtils playMidi];
	if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive)
	{
		// user has tapped notification
//		[[HOUIMgr sharedInstance] sendCommand:kHO_CMD_gotoMy data:nil];
	}
	else
	{
		// user opened app from app icon
	}
}

- (void)initUIStyle
{
	if (IS_MORETHAN_IOS7)
	{
		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
	}
	else
	{
		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
	}
	//    [[UINavigationBar appearance] setBarTintColor:MAIN_COLOR_NORMAL];
	
	[[UINavigationBar appearance] setBackgroundImage:[HOUtils createImageWithColor:MAIN_COLOR_NORMAL forRect:CGRectMake(0, 0, [HOUtils getScreenWidth], 69)] forBarMetrics:UIBarMetricsDefault];
	
	[[UINavigationBar appearance]  setShadowImage:[[UIImage new] autorelease]];
}
#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
- (void)initSocial
{
	
	//设置友盟社会化组件appkey
//	NSString *UmengAppkey = UMENG_APPKEY;
//	[UMSocialData setAppKey:UmengAppkey];
//	
//	//打开调试log的开关
//	[UMSocialData openLog:YES];
//	
//	//如果你要支持不同的屏幕方向，需要这样设置，否则在iPhone只支持一个竖屏方向
//	[UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskAll];
//	
//	// 打开新浪微博的SSO开关
//	// 将在新浪微博注册的应用appkey、redirectURL替换下面参数，并在info.plist的URL Scheme中相应添加wb+appkey，如"wb3921700954"，详情请参考官方文档。
//	[UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"13241507"
//											  secret:@"57bc36011b993c4f06a9658c4596832f"
//										 RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];



	
//	[UMSocialData setAppKey:@"jrYuGn6SV4WFnkpvxaJP2SEXb"];
//////	//默认使用iOS自带的Twitter分享framework，在iOS 6以上有效。若要使用我们提供的twitter分享需要使用此开关：
//	[UMSocialTwitterHandler openTwitter];
//////	// 集成的TwitterSDK仅在iOS7.0以上有效，在iOS 6.x上自动调用系统内置Twitter授权
//	if (IS_MORETHAN_IOS7) {
//		[UMSocialTwitterHandler setTwitterAppKey:@"jrYuGn6SV4WFnkpvxaJP2SEXb"  withSecret:@"uq2RgMJqFx5Qpo5XUR4ya7UDGqiSlaS8InjDH8iDXoOKBGopCt"];
//	}
//    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToFacebook,UMShareToWechatSession, UMShareToSina]];
}



- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
	
	[JSHAREService handleOpenUrl:url];
    // 接受传过来的参数
//    NSString *text = [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"打开啦"
//                                                        message:text
//                                                       delegate:nil
//                                              cancelButtonTitle:@"OK"
//                                              otherButtonTitles:nil];
//    [alertView show];
    return YES;
}

//仅支持 iOS9 以上系统，iOS8 及以下系统不会回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
	[JSHAREService handleOpenUrl:url];
	return YES;
}

@end
